package linkedlist;

/**
 * @Author Fizz Pu
 * @Date 2021/5/15 下午7:59
 * @Version 1.0
 * 失之毫厘，缪之千里！
 */

import DFS.ListNode;

import java.util.Arrays;
import java.util.HashSet;

/**
 * 输入两个递增排序的链表，合并这两个链表并使新链表中的节点仍然是递增排序的。
 *
 * 示例1：
 *
 * 输入：1->2->4, 1->3->4
 * 输出：1->1->2->3->4->4
 *
 * 来源：力扣（LeetCode）
 * 链接：https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof
 * 著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。
 */


// 这道题目虽然简单, 但是引入一些头节点可以避免处理一些细节

public class MergerLinkedOffer25 {
    public static void main(String[] args) {
        new HashSet<>().addAll(Arrays.asList(new int[] {1,2}));
    }
    public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
        ListNode fakeHead = new ListNode(0);
        ListNode current = fakeHead;
        ListNode p1 = l1;
        ListNode p2 = l2;

        while (p1 != null && p2 != null){
            if(p1.val < p2.val){
                current.next = p1;
                p1 = p1.next;
                current = current.next;
                continue;
            }

            current.next = p2;
            p2 = p2.next;
            current = current.next;
        }

        if (p1 != null){
            current.next = p1;
        }

        if (p2 != null){
            current.next = p2;
        }

        return fakeHead.next;



        /*ListNode head = null;
        ListNode current = null;
        ListNode p1 = l1;
        ListNode p2 = l2;
        ListNode tmp = null;

        while(p1 != null && p2 != null){
            if(p1.val < p2.val){
                if(current == null){
                    current = p1;
                    tmp = current.next;
                    current.next = null;
                    p1 = tmp;
                } else {
                    current.next = p1;
                    p1 = p1.next;
                }

            } else{
                if(current == null){
                    current = p2;
                    tmp = current.next;
                    current.next = null;
                    p2 = tmp;
                } else{
                    current.next = p2;
                    p2 = p2.next;
                }

            }
            if(head == null){
                head = current;
            }

            if(current.next != null){
                current = current.next;
            }
        }

        if(p1 != null){
            if(current != null){
                current.next = p1;
            } else{
                head = current = p1;
            }
        }

        if(p2 != null){
            if(current != null){
                current.next = p2;
            } else{
                head = current = p2;
            }
        }

        return head;*/
    }
}
